package com.modelo.dao.rolsubtarea;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;

import com.modelo.dao.comun.HibernateBaseDAO;
import com.modelo.entity.Rol;
import com.modelo.entity.Rolsubtarea;

@Repository
public class RolsubtareaDAO extends HibernateBaseDAO<Rolsubtarea> implements IRolSubtareaDAO,
		Serializable {

	private static final Logger log = LoggerFactory.getLogger(RolsubtareaDAO.class);
	private static final long serialVersionUID = 1L;

	public static RolsubtareaDAO getFromApplicationContext(ApplicationContext ctx) {
		return (RolsubtareaDAO) ctx.getBean("RolsubtareaDAO");
	}

	@Autowired
	public RolsubtareaDAO(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	public List<Rolsubtarea> findByExample(Rolsubtarea instance) {
		log.debug("finding Rolsubtarea instance by example");
		try {
			List<Rolsubtarea> results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Rolsubtarea instance with property: " + propertyName + ", value: "
				+ value);
		try {
			String queryString = "from Rolsubtarea as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	@Override
	public List<Rolsubtarea> getSubtareasFromRol(Rol r) {
		Criteria consulta = getSession().createCriteria("com.modelo.entity.Rolsubtarea");
		consulta.setFetchMode("subtarea", FetchMode.JOIN);
		// De esta forma hacemos que traiga tambien las tareas de subtarea
		consulta.setFetchMode("subtarea.tarea", FetchMode.JOIN);
		consulta.add(Restrictions.eq("rol", r));

		return consulta.list();
	}

	@Override
	protected void initDao() {

	}

}